What is a Class in Java?
A class in Java is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In other words, a class is a basic building block of object-oriented programming.
Structure of a Class A class in Java can contain the following components:
Data Members: These are the variables within a class.
Methods: These are the functions within a class.
Constructors: These are the special methods that are used to initialize objects.
Nested Classes and Interfaces: A class can contain another class or an interface.
Here’s a general syntax for declaring a class in Java:
Class basic syntax
class {
// Data members
// Methods
}
Example of a Class in Java Let’s consider a simple example of a class in Java, a Calculate class:
Class structure example - arithmetic operations
public class Main{
int a;
int b;
public Main(int x, int y) {
this.a = x;
this.b = y;
}
public int add() {
int res = a + b;
return res;
}
public int subtract() {
int res = a - b;
return res;
}
public int multiply() {
int res = a * b;
return res;
}
public int divide() {
int res = a / b;
return res;
}
public static void main(String[] args) {
Main c1 = new Main(45, 4);
System.out.println("Addition is :" + c1.add());
System.out.println("Subtraction is :" + c1.subtract());
System.out.println("Multiplication is :" + c1.multiply());
System.out.println("Division is :" + c1.divide());
}
}
Output
Addition is :49
Subtraction is :41
Multiplication is :180
Division is :11
In this example, Calculate is a class that has two data members (a and b), four methods (add, subtract, multiply, divide), and a constructor. The main method creates an object of the Calculate class and calls its methods.